/**
 * 异常数据自动预警系统
 */
import React, { useEffect, useState } from 'react';
import { AlertTriangle, X } from 'lucide-react';

interface Alert {
  id: string;
  type: 'warning' | 'error' | 'info';
  title: string;
  message: string;
  reason?: string;
  suggestion?: string;
  timestamp: Date;
}

interface AlertSystemProps {
  alerts: Alert[];
  onDismiss?: (id: string) => void;
}

const AlertSystem: React.FC<AlertSystemProps> = ({ alerts, onDismiss }) => {
  const [visibleAlerts, setVisibleAlerts] = useState<Alert[]>([]);

  useEffect(() => {
    // 只显示最新的3条预警
    setVisibleAlerts(alerts.slice(0, 3));
  }, [alerts]);

  if (visibleAlerts.length === 0) return null;

  return (
    <div className="fixed bottom-4 right-4 z-50 space-y-3 max-w-md">
      {visibleAlerts.map((alert) => (
        <div
          key={alert.id}
          className={`rounded-lg shadow-xl p-4 border-l-4 animate-pulse ${
            alert.type === 'error'
              ? 'bg-red-50 border-red-500'
              : alert.type === 'warning'
              ? 'bg-orange-50 border-orange-500'
              : 'bg-blue-50 border-blue-500'
          }`}
        >
          <div className="flex items-start gap-3">
            <AlertTriangle
              size={20}
              className={`mt-0.5 ${
                alert.type === 'error' ? 'text-red-500' : alert.type === 'warning' ? 'text-orange-500' : 'text-blue-500'
              }`}
            />
            <div className="flex-1">
              <div className="flex items-center justify-between mb-1">
                <h4 className="font-bold text-gray-800">{alert.title}</h4>
                {onDismiss && (
                  <button
                    onClick={() => onDismiss(alert.id)}
                    className="text-gray-400 hover:text-gray-600"
                  >
                    <X size={16} />
                  </button>
                )}
              </div>
              <p className="text-sm text-gray-700 mb-2">{alert.message}</p>
              {alert.reason && (
                <div className="text-xs text-gray-600 mb-1">
                  <span className="font-medium">异常原因：</span>
                  {alert.reason}
                </div>
              )}
              {alert.suggestion && (
                <div className="text-xs text-blue-600 bg-blue-50 p-2 rounded mt-2">
                  <span className="font-medium">处理建议：</span>
                  {alert.suggestion}
                </div>
              )}
              <div className="text-xs text-gray-400 mt-2">
                {alert.timestamp.toLocaleTimeString('zh-CN')}
              </div>
            </div>
          </div>
        </div>
      ))}
    </div>
  );
};

export default AlertSystem;
